﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleAlgorithms.Tests
{
    /// <summary>
    /// 本示例演示了使用Taylor级数展开求三角函数的示例。
    /// </summary>
    public class EX101_TaylorForSin: ITestable
    {
        public void Test()
        {
            Console.WriteLine("-------------- 特定值测试 --------------");
            double[] vs = { 0, Math.PI / 6, Math.PI / 4, Math.PI / 2 };
            foreach (var v in vs)
            {
                double sinX = CalculateSin(v);
                Console.WriteLine($"Sin({v}) = {sinX:0.0000000000}");
            }


            Console.WriteLine("-------------- 迭代次数测试 --------------");
            double x = Math.PI / 6;
            for (int n = 1; n < 10; n++)
            {
                double sinX = CalculateSin(x, n);
                Console.WriteLine($"n = {n}: Sin({x}) = {sinX:0.0000000000}");
            }
        }

        public double CalculateSin(double x, int n = 20)
        {
            double sinVal = 0;
            for (int i = 0; i < n; i++)
            {
                sinVal += Math.Pow(-1, i) * (Math.Pow(x, 2 * i + 1) / Factorial(2 * i + 1));
            }
            return sinVal;
        }

        public double Factorial(int num)
        {
            double fact = 1;
            for (int i = 1; i <= num; i++)
            {
                fact *= i;
            }
            return fact;
        }
    }
}
